package cn.edu.swu.cly.auth;

import cn.edu.swu.cly.repo.DatabaseService;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        String username = request.getParameter("user");
        String password = request.getParameter("pass");
        String code = request.getParameter("code");

        验证码检验
        HttpSession session = request.getSession();
        String captcha = session.getAttribute(CaptchaServlet.CAPTCHA_KEY);
        if(captcha == null || !captcha.equalsIgnoreCase(code) ) {
            response.sendRedirect("./login.html");
            return;
        }

        //从容器获取数据库访问类
        ServletContext context = request.getServletContext();
        DatabaseService service = (DatabaseService) context.getAttribute(DatabaseService.CONTEXT_KEY);       //强制转换，获取状态
        try {

            //构造一个查询sql
            List<User> users = service.query(
                    String.format("select * from user where name='%s' and passwd=md5('%s')", username, password),
                    new UserResultSetVisitor()      //第三个参数是query要求的参数，返回的集合
            );

            if (users.size() > 0) {
                this.loginToken(request, users.get(0));
                response.sendRedirect("./admin/books");
            } else {
                response.sendRedirect("./login.html");
            }
        } catch (IOException | SQLException e) {
            throw new ServletException(e);
        }
    }


    //用户登陆成功就分配状态标记
    private void loginToken(HttpServletRequest request, User user) {
        HttpSession session = request.getSession(true);
        session.setAttribute(AuthFilter.LOGIN_TOKEN_KEY, user);        //键值对，键定义在AuthFilter中

    }
}

